package cn.edu.sdjzu.xg.kcsj.controller.basic;

import cn.edu.sdjzu.xg.kcsj.domain.Faculty;
import cn.edu.sdjzu.xg.kcsj.exception.BysjException;
import cn.edu.sdjzu.xg.kcsj.service.FacultyService;
import cn.edu.sdjzu.xg.kcsj.util.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;

@WebServlet("/findSchoolFromFaculty")
public class FindSchoolController extends HttpServlet {
    // 记录器，可以控制日志信息输出到控制台，替代输出语句
    private static final Logger log = LogManager.getLogger(FindSchoolController.class);

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 创建JSONObject对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        try {
            // 如果为空直接往前台响应"未收到请求信息"
            if (request == null){
                message.put("message","未收到请求信息");
                log.debug("未收到请求信息");
                response.getWriter().println(message);
            }else { // 请求不为空
                Collection<Faculty> allSchool = FacultyService.getInstance().findAllSchool();
                message.put("data",allSchool);
                response.getWriter().println(message);
            }
        } catch (BysjException e) {
            message.put("message", e.getMessage());
            //响应message到前端
            response.getWriter().println(message);
            // 在命令行打印异常信息在程序中出错的位置及原因
            e.printStackTrace();
        } catch (SQLException e) {
            message.put("message", "数据库操作异常");
            response.getWriter().println(message);
            e.printStackTrace();
        } catch (Exception e) {
            message.put("message", "网络异常");
            response.getWriter().println(message);
            e.printStackTrace();
        }
    }
}
